import time
import can


def can_open():  # 开启can通讯
    os.system('sudo ip link set can0 type can bitrate 250000')
    os.system('sudo ifconfig can0 up')


# channel_name为do的位置，如果输入0则为操作全部，switch是开光状态0为关，1为开
def can_relay_board_do_control(channel_name, switch):
    # 设置CAN接口（请替换为你的CAN接口）
    can_interface = "can0"
    # 设置CAN消息的ID和数据（请替换为你的实际值）
    can_id = 0x0101
    if switch not in {0, 1}:
        print("Error: Invalid value for switch. It must be 0 or 1.")
        return None

    if not isinstance(channel_name, int) or channel_name < 0 or channel_name > 255:
        print("Error: Invalid value for channel_name. It must be a number between 0 and 255.")
        return None
    channel_byte = [channel_name & 0xFF]
    switch_byte = [switch & 0xFF]

    can_data = [eval('0x{:02X}'.format(channel_byte[0])), eval('0x{:02X}'.format(switch_byte[0])), 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00]

    # 创建CAN总线对象
    bus = can.interface.Bus(channel=can_interface, bustype='socketcan')

    # 创建CAN消息对象
    message = can.Message(arbitration_id=can_id, data=can_data, is_extended_id=False)

    try:
        # 发送CAN消息
        bus.send(message)
        message_read = bus.recv(timeout=1)  # 接收数据

        print(f"Sent CAN message: {message}")
        print(f"Read CAN message: {message_read.data}")
        print(f"Read CAN message ID: {message_read.arbitration_id}")
    except can.CanError:
        print("Error sending CAN message")


if __name__ == "__main__":
    # 操作示例
    # can_open()
    # can_relay_board_do_control(0, 1)  # 开启全部
    # time.sleep(1)
    # can_relay_board_do_control(0, 0)  # 关闭全部
    # time.sleep(1)
    # can_relay_board_do_control(1, 1)  # 开启通道1
    # time.sleep(1)
    # can_relay_board_do_control(1, 0)  # 关闭通道1
    # time.sleep(1)
    # can_relay_board_do_control(2, 1)  # 开启通道2
    # time.sleep(1)
    # can_relay_board_do_control(2, 0)  # 关闭通道2
    for i in range(1, 25):
        can_relay_board_do_control(i, 1)
        time.sleep(1)
        print(i)
    for i in range(1, 25):
        can_relay_board_do_control(i, 0)
        time.sleep(1)
        print(i)
